package edu.vt.ece_3574.amber_alert.database;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;

import com.google.android.maps.GeoPoint;

import android.os.AsyncTask;
import android.util.Log;
import edu.vt.ece_3574.amber_alert.accounts.Account;
import edu.vt.ece_3574.amber_alert.accounts.Friend;

public class UpdateAccountOnServer extends AsyncTask<Void, Void, Void> {
	private Account account;

	public UpdateAccountOnServer(Account account) {
		this.account = account;
	}

	@Override
	protected Void doInBackground(Void... params) {
		
		InputStream is = null;
		String result = "";
		
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("serialNum", account.getSerialNumber()));
		nameValuePairs.add(new BasicNameValuePair("name", account.getName()));
		nameValuePairs.add(new BasicNameValuePair("password", account.getPassword()));
		nameValuePairs.add(new BasicNameValuePair("phoneNumber", account.getNumber()));
		nameValuePairs.add(new BasicNameValuePair("type", account.getType()));
		if (account.getLastLocation() == null) {
			nameValuePairs.add(new BasicNameValuePair("location", ""));
		}
		else {
			nameValuePairs.add(new BasicNameValuePair("location", convertLocationToString(account.getLastLocation())));
		}
		nameValuePairs.add(new BasicNameValuePair("associations", convertAssociationsToString(account.getAssociatedAccountNames())));
		nameValuePairs.add(new BasicNameValuePair("friends", convertFriendsToString(account.getAssociatedFriends())));
		
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(DatabaseHandler.databaseURL + "updateAccount.php");
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost); 
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}
		catch(Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result=sb.toString();
		}
		catch (Exception e) {
			Log.e("log_tag", "Error converting result "+e.toString());
		}
		//parse json data
		try{
			new JSONArray(result);
		}
		catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private String convertLocationToString(GeoPoint location) {
		String longitudeString = Double.toString(location.getLongitudeE6());
		String latitudeString = Double.toString(location.getLatitudeE6());
		return longitudeString + ":" + latitudeString;
	}
	
	private String convertAssociationsToString(ArrayList<String> associationsArray) {
		String associationsString = "";
		for (String associatedAccount : associationsArray) {
			if (DatabaseHandler.get().determineIfUserExistsOnServer(associatedAccount)) {
				associationsString += ";" + associatedAccount;
			}
		}
		
		return associationsString;
	}

	private String convertFriendsToString(ArrayList<Friend> associatedFriends) {
		String friendsString = "";
		for (Friend friend : associatedFriends) {
			friendsString += ";" + friend.getName() + ":" + friend.getNumber() + ":" + friend.getAddress();
		}
		
		return friendsString;
	}
}
